import request from '@/utils/request';

// 图片类型映射
const IMAGE_TYPES = {
  SUNLIT_PEAK: {
    horizontal: 61,
    vertical: 62
  },
  BLUE_MOON: {
    horizontal: 71,
    vertical: 72
  },
  SISTER_LAKES: {
    horizontal: 81,
    vertical: 82
  },
  DREAM_SPACE: {
    horizontal: 91,
    vertical: 92
  }
};

// 图片缓存
const imageCache = new Map();

// 处理图片URL
const processImageUrl = (url) => {
  if (!url) return '';
  return url.startsWith('http') ? url : `http://${url}`;
};

// 获取图片列表
const fetchImages = async (type, title, description) => {
  const cacheKey = `${type.horizontal}-${type.vertical}`;
  
  // 检查缓存
  if (imageCache.has(cacheKey)) {
    return imageCache.get(cacheKey);
  }

  try {
    // 并行获取横版和竖版图片
    const [horizontalRes, verticalRes] = await Promise.all([
      request({
        url: `/api/profilepic/GetProfilesAsync?_type=${type.horizontal}`,
        method: 'get'
      }),
      request({
        url: `/api/profilepic/GetProfilesAsync?_type=${type.vertical}`,
        method: 'get'
      })
    ]);

    const allImages = [];
    const imageUrls = new Set(); // 用于去重

    // 处理横版图片
    if (horizontalRes.status && horizontalRes.data) {
      horizontalRes.data.forEach(item => {
        const imageUrl = processImageUrl(item.picUrl);
        if (imageUrl && !imageUrls.has(imageUrl)) {
          imageUrls.add(imageUrl);
          allImages.push({
            image: imageUrl,
            title: title,
            description: description,
            large: true
          });
        }
      });
    }

    // 处理竖版图片
    if (verticalRes.status && verticalRes.data) {
      verticalRes.data.forEach(item => {
        const imageUrl = processImageUrl(item.picUrl);
        if (imageUrl && !imageUrls.has(imageUrl)) {
          imageUrls.add(imageUrl);
          allImages.push({
            image: imageUrl,
            title: title,
            description: description
          });
        }
      });
    }

    // 限制图片数量为6张
    const result = allImages.slice(0, 6);
    
    // 存入缓存
    imageCache.set(cacheKey, result);
    
    return result;
  } catch (error) {
    console.error(`Failed to fetch images for type ${type.horizontal}:`, error);
    throw error;
  }
};

// 获取日照金山图片
export const fetchSunlitPeakImages = () => {
  return fetchImages(
    IMAGE_TYPES.SUNLIT_PEAK,
    "日照金山",
    "金光闪耀，如诗如画"
  );
};

// 获取蓝月谷图片
export const fetchBlueMoonImages = () => {
  return fetchImages(
    IMAGE_TYPES.BLUE_MOON,
    "蓝月谷",
    "碧水蓝天，如梦如幻"
  );
};

// 获取姊妹湖图片
export const fetchSisterLakesImages = () => {
  return fetchImages(
    IMAGE_TYPES.SISTER_LAKES,
    "姊妹湖",
    "双湖映月，相映成趣"
  );
};

// 获取梦幻空间图片
export const fetchDreamSpaceImages = () => {
  return fetchImages(
    IMAGE_TYPES.DREAM_SPACE,
    "梦幻空间",
    "光影交错，梦幻迷离"
  );
};

// 清除缓存
export const clearImageCache = () => {
  imageCache.clear();
};

// 获取缓存大小
export const getCacheSize = () => {
  return imageCache.size;
}; 